package services

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	"zwai-app/db"
	"zwai-app/models"
)

// UserSummary 用于返回简要的用户信息
type UserSummary struct {
	UserID   string `json:"userId"`
	Account  string `json:"account"`
	Username string `json:"username"`
}

// FollowAuthor 切换关注/取消关注作者
func FollowAuthor(ctx context.Context, authorID, userID primitive.ObjectID) error {
	// 不能关注自己
	if authorID == userID {
		return errors.New("cannot follow yourself")
	}

	userColl := db.Client.Database(db.DBName).Collection("User")

	// 先尝试取消关注
	res, err := userColl.UpdateOne(ctx,
		bson.M{"_id": authorID, "followers": bson.M{"$in": bson.A{userID}}},
		bson.M{"$pull": bson.M{"followers": userID}},
	)
	if err != nil {
		return err
	}
	if res.ModifiedCount > 0 {
		// 也要把自己文档中的 following 去掉
		_, _ = userColl.UpdateOne(ctx,
			bson.M{"_id": userID},
			bson.M{"$pull": bson.M{"following": authorID}},
		)
		return nil
	}

	// 如果没取消成功，就新增关注
	if _, err := userColl.UpdateOne(ctx,
		bson.M{"_id": authorID},
		bson.M{"$addToSet": bson.M{"followers": userID}},
	); err != nil {
		return err
	}
	// 把自己文档的 following 加上 authorID
	if _, err := userColl.UpdateOne(ctx,
		bson.M{"_id": userID},
		bson.M{"$addToSet": bson.M{"following": authorID}},
	); err != nil {
		return err
	}
	return nil
}

// GetFollowers 返回关注了 userID 的所有用户
func GetFollowers(ctx context.Context, userIDStr string) ([]UserSummary, error) {
	uid, err := primitive.ObjectIDFromHex(userIDStr)
	if err != nil {
		return nil, errors.New("invalid user ID")
	}
	userColl := db.Client.Database(db.DBName).Collection("User")
	cursor, err := userColl.Find(ctx, bson.M{"following": uid})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	var list []UserSummary
	for cursor.Next(ctx) {
		var u models.User
		if err := cursor.Decode(&u); err != nil {
			continue
		}
		list = append(list, UserSummary{
			UserID:   u.ID.Hex(),
			Account:  u.Account,
			Username: u.Username,
		})
	}
	return list, nil
}

// GetFollowing 返回 userID 关注的所有用户
func GetFollowing(ctx context.Context, userIDStr string) ([]UserSummary, error) {
	uid, err := primitive.ObjectIDFromHex(userIDStr)
	if err != nil {
		return nil, errors.New("invalid user ID")
	}
	userColl := db.Client.Database(db.DBName).Collection("User")

	// 先查出自己的 following 数组
	var u models.User
	if err := userColl.FindOne(ctx, bson.M{"_id": uid}).Decode(&u); err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, nil
		}
		return nil, err
	}
	if len(u.Following) == 0 {
		return nil, nil
	}

	// 再批量根据 ID 查用户
	cursor, err := userColl.Find(ctx, bson.M{"_id": bson.M{"$in": u.Following}})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	var list []UserSummary
	for cursor.Next(ctx) {
		var f models.User
		if err := cursor.Decode(&f); err != nil {
			continue
		}
		list = append(list, UserSummary{
			UserID:   f.ID.Hex(),
			Account:  f.Account,
			Username: f.Username,
		})
	}
	return list, nil
}
